import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from "../store"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    require: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue'),
    redirect: '/user/cart',
    children: [
      {
        path: 'cart', component: () => import(/* webpackChunkName: "user" */ '../components/user/Cart.vue'),

      }
    ]
    // 路由独享守卫
    // beforeEnter: (to, from, next) => {
    //   console.log("user-路由独享守卫", to, from);
    //   let token = localStorage.getItem("x-auth-token");
    //   if (token) {
    //     next();
    //   } else {
    //     // alert("请先登录")
    //     store.dispatch('ShowToast/asyncChangeIsShowToast', {
    //       isshow: true,
    //       msg: '请先登录',
    //       type: 'danger'
    //     })
    //   }
    // },
  },
  {
    path: '/details',
    name: 'details',
    component: () => import(/* webpackChunkName: "details" */ '../views/Details.vue')
  },
  {
    path: '*',
    name: "error",
    component: () => import(/* webpackChunkName: "details" */ '../components/Error.vue')
  }



]

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由全局前置守卫
// router.beforeEach((to, form, next) => {
//   // to:Route:即将要进入的目标，路由对象
//  //from：Router：当前导航正要离开的路由
//  //next：Function：一定要调用该方法来resolve 这个钩子
//  // 当去user页面时，需要进行是否登录判断。如果已经登录，正常进入user,
// //否则不进入提示先登录
//   if (to.path == "/user") {
//     console.log("打开user页面");
//     let token = localStorage.getItem("x-auth-token");
//     if (token) {
//       next();
//     } else {
//       // alert("请先登录")
//       store.dispatch('ShowToast/asyncChangeIsShowToast', {
//         isshow: true,
//         msg: '请先登录',
//         type: 'danger'
//       })
//     }
//     return;
//   }
//   next()
// })



export default router
